package org.linlinjava.litemall.core.util.paymentCodeUtil;

import org.linlinjava.litemall.core.exception.EncryptionException;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Base64;
import java.util.Date;

public class EncryptionUtils {
    private static final String SECRET_KEY = "lumiere#cafe@com"; // 固定密钥

    public static String encrypt(String input) throws Exception {
        // 获取当前时间戳加30秒
        Date now = new Date();
        long timestamp = (now.getTime() / 1000) + 60;
        String data = input + ";" + timestamp;

        // 初始化密钥和加密算法
        Key key = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);

        // 执行加密操作
        byte[] encryptedData = cipher.doFinal(data.getBytes());

        // 对加密结果进行Base64编码
        return Base64.getEncoder().encodeToString(encryptedData);
    }

    public static String decrypt(String input) throws Exception {
        // 对Base64编码的加密数据进行解码
        byte[] encryptedData = Base64.getDecoder().decode(input);

        // 初始化密钥和解密算法
        Key key = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key);

        // 执行解密操作
        byte[] decryptedData = cipher.doFinal(encryptedData);
        String data = new String(decryptedData);

        // 分离数据和时间戳
        String[] parts = data.split(";");
        String decrypted = parts[0];
        long timestamp = Long.parseLong(parts[1]);

        // 判断时间戳是否过期
        Date now = new Date();
        long currentTimestamp = now.getTime() / 1000;
        if (timestamp < currentTimestamp) {
            throw new EncryptionException("Expired data");
        }

        return decrypted;
    }

   /* public static void main(String[] args) {
        try {
            // 测试加密解密
            String input = "47387387483";
            String encrypted = encrypt(input);
            String decrypted = decrypt(encrypted);

            System.out.println("Original data: " + input);
            System.out.println("Encrypted data: " + encrypted);
            System.out.println("Decrypted data: " + decrypted);

            // 测试过期数据
            Thread.sleep(31000); // 等待31秒
            decrypt(encrypted); // 期望抛出异常：Expired data
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/
}
